<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>

<template>
  <div class="div-relative">
    <Row :gutter="10">
      <Card>
        <div class="table-head" v-show="selectionArr.length == 0">
          日期：
          <DatePicker type="date"
                      format="yyyy-MM-dd"
                      :confirm="true"
                      :transfer="true"
                      :editable="false"
                      @on-ok="DatePickerOK"
                      @on-clear="DatePickerOnClear"
                      @on-open-change="DatePickerOnOpenChange"
                      placement="bottom-start"
                      placeholder="请选择日期"
                      v-model="DatePickerValue"
                      style="width: 200px;"></DatePicker>
          &nbsp;&nbsp;
          部门：
          <Select v-model="departmentId" :transfer="true" @on-change="onChangedepartmentArr" style="width: 200px;">
            <Option v-for="item in departmentArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>

          <Button type="text" icon="ios-podium" class="Button" @click="frequencyFun()">统计</Button>
          <Button type="text" icon="ios-cloud-download" class="Button" @click="showExport()">导出
          </Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data"
                 @on-selection-change="selectionChange" ref="selectionTable"></Table>
        </Row>
      </Card>
      <!--统计-->
      <Drawer :closable="false" :width="DrawerWidth" v-model="user_retired" class="Drawer-body">
        <div class="Drawer_pStyle">
          <span></span>
          <span class="del" @click="hidefrequency"><Button type="error" size="small" icon="md-close"></Button></span>
        </div>
        <div class="body frequency-body">
          <div class="table-head">
            时间段：
            <DatePicker type="daterange"
                        format="yyyy-MM-dd"
                        :confirm="true"
                        :transfer="true"
                        :editable="false"
                        :clearable="false"
                        split-panels
                        @on-ok="frequency_DatePickerOK"
                        @on-clear="frequency_DatePickerOnClear"
                        @on-open-change="frequency_DatePickerOnOpenChange"
                        placement="bottom-start"
                        placeholder="请选择日期"
                        v-model="frequency_DatePickerValue"
                        style="width: 200px"></DatePicker>
            &nbsp;&nbsp;
            部门：
            <Select v-model="departmentId" :transfer="true" @on-change="frequency_onChangeDepartment"
                    style="width:200px">
              <Option v-for="item in departmentArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </div>
          <div class="charts" id="charts-div" v-show="(checkInListArr.length > 0)"></div>

          <Row class="margin-top-10 margin-bottom-70" v-show="(checkInListArr.length > 0)">
            <Table stripe border :columns="columns_list" :data="checkInListArr"></Table>
          </Row>

          <div class="not-charts" v-show="!(checkInListArr.length > 0)">
            <div class="show">暂无统计信息</div>
          </div>
        </div>
        <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
          <Button type="text" @click="hidefrequency">取消</Button>
        </div>
      </Drawer>
      <!--导出-->
      <Modal v-model="showExportData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">导出信息</h3>
        <Form label-position="top">
          <FormItem label="导出类型">
            <Select v-model="exprot.type" :transfer="true" style="width:100%;">
              <Option v-for="item in exprot.typeArr" :value="item.id" :key="item.id">{{ item.title }}</Option>
            </Select>
          </FormItem>
          <FormItem label="部门" v-if="exprot.type != 'vacation'">
            <Select v-model="exprot.departmentId" :transfer="true" style="width:100%;">
              <Option v-for="item in exprot.departmentArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="时间段">
            <DatePicker type="daterange"
                        format="yyyy-MM-dd"
                        :confirm="true"
                        :transfer="true"
                        :editable="false"
                        :clearable="false"
                        split-panels
                        @on-ok="exprot_DatePickerOK"
                        @on-clear="exprot_DatePickerOnClear"
                        @on-open-change="exprot_DatePickerOnOpenChange"
                        placement="bottom-start"
                        placeholder="请选择日期"
                        v-model="exprot.DatePickerValue"
                        style="width: 100%;"></DatePicker>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="asyncOK">取消</Button>
          <Button type="primary" @click="ExportData()">确定</Button>
        </div>
      </Modal>
    </Row>
    <spin-page :showSpin="showSpin"></spin-page>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  import chartsBar from '../home/components/chartsBar.vue';
  import spinPage from '../components/spin-page.vue';
  import echarts from 'echarts';
  export default {
    components: {
      chartsBar,
      spinPage
    },
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        order_by: [{field: "department", sort: "desc"}],
        id: '',
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
//          {
//            type: 'selection',
//            width: 60,
//            align: 'center'
//          },
          {
            key: 'name',
            title: '姓名',
            align: 'center',
          },
          {
            key: 'department',
            title: '部门',
            align: 'center',
          },
          {
            key: 'up_time',
            title: '上班时间',
            align: 'center',
          },
          {
            key: 'after_time',
            title: '下班时间',
            align: 'center',
          },
        ],
        data: [],
        dataDetail: {},
        initTable: [],
        DatePickerValue: '',
        from: '',
        to: '',
        // 统计
        user_retired: false,
        frequency_DatePickerValue: [],
        frequency_from: '',
        frequency_to: '',
        Month: '',
        department: 1,
        charts_id: 'frequency_div_id',
        charts_title: '',
        charts_series_name: '出勤率',
        charts_xDataArr: [],
        charts_yDataArr: [],
        DrawerWidth: Util.constant.DrawerWidth,// 抽屉的宽度
        WindowWidth: Util.constant.WindowWidth,// 窗口的宽度
        WindowHeight: Util.constant.WindowHeight,// 窗口的高度
        showSpin: false,//加载中
        selectionArr: [],
        searchDepModal: false,// 选部门
        depsTreeData: [],
        searchDeps: [],
        searchDepartments: [],

        departmentArr: [],
        departmentId: 0,

        showExportData: false,
        exprot: {
          departmentArr: [],
          departmentId: 0,
          DatePickerValue: [],
          from: '',
          to: '',
          type: 'vacation',
          typeArr: [
            {
              id: 'vacation',
              title: '请假',
            },
            {
              id: 'sign-in',
              title: '考勤',
            }
          ],
        },
        checkInListArr: [],
        columns_list: [
          {
            key: 'name',
            title: '姓名',
            align: 'center',
          },
          {
            key: 'department',
            title: '部门',
            align: 'center',
          },
          {
            key: 'attendance',
            title: '到岗 (天)',
            align: 'center',
          },
          {
            key: 'vacation',
            title: '请假 (天)',
            align: 'center',
          },
          {
            key: 'absent',
            title: '缺勤 (次)',
            align: 'center',
          },
        ],
      };
    },
    mounted () {
      var _this = this;
      var date = Utils.dateToDate(new Date());
      _this.DatePickerValue = date;
      _this.from = date;

      _this.getdepartment();
    },
    methods: {
      DatePickerOK: function () {
        var _this = this;
      },
      DatePickerOnClear: function () {
        var _this = this;
        _this.DatePickerValue = '';
      },
      DatePickerOnOpenChange: function (open) {
        var _this = this;
        if (open == false) {// 关闭了日历
          var DatePickerValue = _this.DatePickerValue;
          _this.from = DatePickerValue == '' ? DatePickerValue : Utils.dateToDate(DatePickerValue);

          _this.getData();
        }
      },
      // 部门筛选
      onChangedepartmentArr: function (val) {
        var _this = this;
        if (val >= 0) {
          _this.departmentId = val;
          _this.getData();
        }
      },
      // 部门列表
      getdepartment: function () {
        var _this = this;
        var data = {};
        var params = {
          url: '/department/getCommunity',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.exprot.departmentArr = [
              {
                id: 0,
                name: '全部'
              }
            ];
            _this.exprot.departmentArr.push(..._data);
            _this.departmentArr = _data;
            _this.departmentId = _data.length > 0 ? _data[0].id : 0;

            _this.getData();
          } else {
            _this.$Message.destroy();
            _this.$Message.error('查询部门列表失败!');
          }
        }
      },
      getData () {
        var _this = this;
        if (_this.from == '') {
          _this.$Message.destroy();
          _this.$Message.error('请选择日期!');
          return false;
        }
        var data = {
          from: _this.from,
          department: _this.departmentId,
        };
        var params = {
          url: '/signin/statistical/statDay',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.showSpin = true;
        function _successFun(res) {
          _this.showSpin = false;
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
            _this.hideNums();
          } else {
            _this.$Message.destroy();
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      show: function (index, data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
        _this.showExportData = false;
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 取消列表选中
      hideNums: function () {
        var _this = this;
        this.$refs.selectionTable.selectAll(false);
        _this.selectionArr = [];
      },

      // 统计
      frequencyFun: function () {
        var _this = this;
        // 当前月
        var day1 = new Date();
        var endyear = Utils.fix(day1.getFullYear(), 4);
        var endmonth = Utils.fix(parseInt(day1.getMonth() + 1), 2);
        var from = endyear + "-" + endmonth + "-01";
        var to = Utils.dateToDate(new Date());

        _this.frequency_DatePickerValue = [from, to];
        _this.frequency_from = from;
        _this.frequency_to = to;

        _this.frequency_getData();
        _this.user_retired = true;
      },
      // 统计
      hidefrequency: function () {
        var _this = this;
        _this.user_retired = false;
      },
      frequency_DatePickerOK: function () {
        var _this = this;
      },
      frequency_DatePickerOnClear: function () {
        var _this = this;
        _this.frequency_DatePickerValue[0] = '';
        _this.frequency_DatePickerValue[1] = '';
      },
      frequency_DatePickerOnOpenChange: function (open) {
        var _this = this;
        if (open == false) {// 关闭了日历
          var DatePickerValue = _this.frequency_DatePickerValue;
          var from1 = DatePickerValue[0];
          var to1 = DatePickerValue[1];
          _this.frequency_from = from1 == '' ? from1 : Utils.dateToDate(from1);
          _this.frequency_to = to1 == '' ? to1 : Utils.dateToDate(to1);

          _this.frequency_getData();
        }
      },
      frequency_onChangeDepartment: function (val) {
        var _this = this;
        if (val >= 0) {
          _this.departmentId = val;
          _this.frequency_getData();
        }
      },
      frequency_getData () {
        var _this = this;
        if (_this.frequency_from == '' || _this.frequency_to == '') {
          _this.$Message.destroy();
          _this.$Message.error('请选择时间段!');
          return false;
        }
        var data = {
          department: _this.departmentId,
          from: _this.frequency_from,
          to: _this.frequency_to,
        };
        var params = {
          url: '/signin/statistical/stat',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || {};
            _this.checkInListArr = _data.users || [];
            _this.setEchartsData();
          } else {
            _this.$Message.destroy();
            _this.$Message.error('统计信息失败!');
          }
        }
      },
      setEchartsData: function () {
        var _this = this;
        var checkInListArr = _this.checkInListArr;
        var attendanceArr = [];
        var vacationArr = [];
        var absentArr = [];
        var nameArr = [];
        for (var k in checkInListArr) {
          if (!checkInListArr[k]) {
            continue;
          }
          var name = checkInListArr[k].name;
          var attendance = checkInListArr[k].attendance || 0;
          var vacation = checkInListArr[k].vacation || 0;
          var absent = checkInListArr[k].absent || 0;
          attendanceArr.push(attendance);
          vacationArr.push(vacation);
          absentArr.push(absent);
          nameArr.push(name);
        }
        var Obj = {
          nameArr: nameArr,
          attendanceArr: attendanceArr,
          vacationArr: vacationArr,
          absentArr: absentArr,
        };
        _this.$nextTick(function () {
          _this.initEcharts(Obj);
        });
      },
      initEcharts: function (dataObj) {
        var _this = this;
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('charts-div'));
        var option = {
          color: ['#2196f3', '#006699', '#4cabce', '#e5323e'],
          title: {},
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
          },
          calculable: true,
          legend: {
            orient: 'horizontal',// 'horizontal' ¦ 'vertical'
            x: 'right',
          },
          grid: {
            left: '15',
            right: '15',
            top: '50',
            bottom: '15',
            containLabel: true
          },
          yAxis: {
            nameTextStyle: {},
            type: 'value',
            name: '天',
          },
          xAxis: {
            nameLocation: 'middle',
            type: 'category',
            axisLabel: {
              show: true,
              interval: 0,
              rotate: 45,
              margin: 2,
              textStyle: {}
            },
            data: dataObj.nameArr
          },
          series: [
            {
              name: '到岗',
              type: 'bar',
              data: dataObj.attendanceArr,
              itemStyle: {
                normal: {
                  //以下为是否显示，显示位置和显示格式的设置了
                  label: {
                    show: true,//显示数字
                    position: 'top',
                    formatter: '{c}'
                  }
                }
              }
            },
            {
              name: '请假',
              type: 'bar',
              data: dataObj.vacationArr,
              itemStyle: {
                normal: {
                  //以下为是否显示，显示位置和显示格式的设置了
                  label: {
                    show: true,//显示数字
                    position: 'top',
                    formatter: '{c}'
                  }
                }
              }
            },
            {
              name: '缺勤',
              type: 'bar',
              data: dataObj.absentArr,
              itemStyle: {
                normal: {
                  //以下为是否显示，显示位置和显示格式的设置了
                  label: {
                    show: true,//显示数字
                    position: 'top',
                    formatter: '{c}'
                  }
                }
              }
            },
          ]
        };
        myChart.setOption(option);
      },

      // 导出
      showExport: function () {
        var _this = this;
        _this.showExportData = true;
        _this.exprot.departmentId = 0;
        _this.exprot.DatePickerValue = [];
        _this.exprot.from = '';
        _this.exprot.to = '';
      },
      exprot_DatePickerOK: function () {
        var _this = this;
      },
      exprot_DatePickerOnClear: function () {
        var _this = this;
        _this.exprot.DatePickerValue[0] = '';
        _this.exprot.DatePickerValue[1] = '';
      },
      exprot_DatePickerOnOpenChange: function (open) {
        var _this = this;
        if (open == false) {// 关闭了日历
          var DatePickerValue = _this.exprot.DatePickerValue;
          var from1 = DatePickerValue[0];
          var to1 = DatePickerValue[1];
          _this.exprot.from = from1 == '' ? from1 : Utils.dateToDate(from1);
          _this.exprot.to = to1 == '' ? to1 : Utils.dateToDate(to1);
        }
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var departmentId = _this.exprot.departmentId;
        var DatePickerValue = _this.exprot.DatePickerValue;
        var from = _this.exprot.from;
        var to = _this.exprot.to;
        var type = _this.exprot.type;

        if (from == '' || to == '') {
          _this.$Message.destroy();
          _this.$Message.error('时间段不能为空!');
          return false;
        }

        var fields = [
          {
            field: 'date',
            title: '日期',
            type: 'date',
            order: 1,
          },
          {
            field: 'dname',
            title: '部门',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'uname',
            title: '姓名',
            type: 'varchar',
            order: 3,
          },
          {
            field: 'is_home',
            title: '本部/外勤',
            type: 'varchar',
            order: 4,
          },
          {
            field: 'is_work',
            title: '到岗/离岗',
            type: 'varchar',
            order: 5,
          },
          {
            field: 'status',
            title: '状态',
            type: 'varchar',
            order: 6,
          },
          {
            field: 'time',
            title: '时间',
            type: 'time',
            order: 7,
          },
          {
            field: 'address',
            title: '签到地点',
            type: 'varchar',
            order: 8,
          },
        ];
        if (type == 'vacation') { // 请假
          departmentId = 0;
          fields = [
            {
              field: 'department',
              title: '部门',
              type: 'varchar',
              order: 1,
            },
            {
              field: 'name',
              title: '姓名',
              type: 'varchar',
              order: 2,
            },
            {
              field: 'type',
              title: '请假类型',
              type: 'varchar',
              order: 3,
            },
            {
              field: 'start_time',
              title: '开始时间',
              type: 'datetime',
              order: 4,
            },
            {
              field: 'end_time',
              title: '结束时间',
              type: 'datetime',
              order: 5,
            },
            {
              field: 'status',
              title: '审批状态',
              type: 'varchar',
              order: 6,
            },
            {
              field: 'reason',
              title: '请假原因',
              type: 'varchar',
              order: 7,
            },
          ];
        }
        var ids = [];
        if (departmentId != 0) {
          ids.push(departmentId);
        }

        var fieldsStr = Util.toStr(fields);
        var data = {
          type: type,
          fields: fieldsStr,
          ids: ids,
          from: from + ' 00:00:00',
          to: to + ' 23:59:59',
        };

        var params = {
          url: '/file/db2excle',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.showSpin = true;

        function _successFun(res) {
          _this.showSpin = false;
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            var title = '导出考勤_';
            if (_this.exprot.type == 'vacation') {
              title = '导出请假_';
            }
            Utils.DownloadFile(url, title + date + '.xlsx');
            _this.asyncOK();
          } else {
            _this.$Message.destroy();
            _this.$Message.error('导出信息失败!');
          }
        }
      },
    }
  };
</script>
